﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace good1.Web.Helpers
{

    public class PermaLinks
    {
        public static string CreatePermaLinkPhrase(string title)
        {
            if (String.IsNullOrEmpty(title)) return "";

            // to lowercase, trim extra spaces
            title = title.ToLower().Trim();
            // remove entities
            title = Regex.Replace(title, @"&\w+;", "");

            var len = title.Length;
            var sb = new StringBuilder(len);
            bool prevdash = false;
            char c;

            for (int i = 0; i < title.Length; i++)
            {
                c = title[i];
                if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-')
                {
                    if (!prevdash)
                    {
                        sb.Append('-');
                        prevdash = true;
                    }
                }
                else if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
                {
                    sb.Append(c);
                    prevdash = false;
                }
                if (i == 80) break;
            }

            title = sb.ToString();
            // remove trailing dash, if there is one
            if (title.EndsWith("-"))
                title = title.Substring(0, title.Length - 1);
            return title;
        }
    }
}
